package com.module.framework.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.module.framework.constants.SystemConstants;
import com.module.framework.domain.Category;
import com.module.framework.domain.Product;
import com.module.framework.dto.ProductListDTO;
import com.module.framework.enums.AppHttpCodeEnum;
import com.module.framework.exception.SystemException;
import com.module.framework.mapper.ProductMapper;
import com.module.framework.service.CategoryService;
import com.module.framework.service.ProductService;
import com.module.framework.utils.BeanCopyUtils;
import com.module.framework.vo.PageVO;
import com.module.framework.vo.ProductDetailVO;
import com.module.framework.vo.ProductListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author JiHuiQin
 * @Date 2022/2/12 18:56
 * @Version 1.0
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ProductMapper productMapper;

	@Value("${absoluteImgPath}")
	String absoluteImgPath;

	@Value("${sonImgPath}")
	String sonImgPath;

	@Override
	public PageVO productList(ProductListDTO productListDTO) {
		Integer categoryId = productListDTO.getCateId();
		Integer pageNum = productListDTO.getPageNum();
		String name = productListDTO.getName();

		LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Product::getStatus, SystemConstants.S_ZERO_FLAG);
		// 如果有categoryId就进行查询，没有就不查询
		queryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0, Product::getCateId, categoryId);
		queryWrapper.like(Objects.nonNull(name), Product::getName, name);
		PageVO pageVO = null;
		if (pageNum == null && productListDTO.getPageSize() == null) {
			List<Product> lists = list(queryWrapper);
			// 查询categoryName
			for (Product list : lists) {
				Category category = categoryService.getById(list.getCateId());
				list.setCategoryName(category.getName());
			}
			List<ProductListVO> productListVOS = BeanCopyUtils.copyBeanList(lists, ProductListVO.class);
			pageVO = new PageVO(productListVOS, productListVOS.size());
		} else {
			//分页查询
			Integer pageSize = productListDTO.getPageSize() == null ? SystemConstants.PAGE_SIZE : productListDTO.getPageSize();
			Page<Product> page = new Page<>(pageNum, pageSize);
			page(page, queryWrapper);

			// 查询categoryName
			List<Product> records = page.getRecords();
			for (Product record : records) {
				Category category = categoryService.getById(record.getCateId());
				record.setCategoryName(category.getName());
				// 图片完整路径
				record.setPic(absoluteImgPath + record.getPic());
			}
			// bean拷贝
			List<ProductListVO> productListVOS = BeanCopyUtils.copyBeanList(page.getRecords(), ProductListVO.class);
			pageVO = new PageVO(productListVOS, (int) page.getTotal());
		}
		return pageVO;
	}

	@Override
	public ProductDetailVO getProductInfo(Integer id) {
		//根据id查询产品信息
		Product product = getById(id);
		ProductDetailVO productDetailVO = BeanCopyUtils.copyBean(product, ProductDetailVO.class);
		//根据分类id查询分类信息
		Integer cateId = product.getCateId();
		Category category = categoryService.getById(cateId);
		if (category != null) {
			productDetailVO.setCategoryName(category.getName());
		}
		return productDetailVO;
	}

	@Override
	public void addProduct(MultipartFile file, String data) {
		// json转为实体类，先转成JSON对象，JSON对象转换成Java对象
		JSONObject jsonObject = JSONObject.parseObject(data);
		Product getProduct = JSONObject.toJavaObject(jsonObject, Product.class);
		Product product = BeanCopyUtils.copyBean(getProduct, Product.class);
		// 获取文件名称
		String fileName = file.getOriginalFilename();
		// 获取文件名后缀
		String suffix = fileName.substring(file.getOriginalFilename().lastIndexOf("."));
		suffix = suffix.toLowerCase();
		if (file != null && (suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png"))) {
			// 随机生成文件名
			fileName = UUID.randomUUID().toString() + suffix;
			String imgUrl = sonImgPath + fileName;
			product.setPic(imgUrl);

			//将上传文件保存到一个目标文档中
			Map<String, String> map = new HashMap<>();
			File dest = new File(absoluteImgPath + fileName);
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
			}
			try {
				file.transferTo(dest);
				map.put("res", "success");
				map.put("url", fileName);
			} catch (IOException e) {
				map.put("res", "error");
			}
		}
		productMapper.insert(product);
	}

	@Override
	public void updateProduct(Product product) {
		productMapper.updateById(product);
	}

	@Override
	public void deleteProduct(Integer id) {
		productMapper.deleteById(id);
	}

}
